package com.seafood.repository;

import com.seafood.entity.Traceability;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 溯源信息数据访问层
 */
@Repository
public interface TraceabilityRepository extends JpaRepository<Traceability, Long>, JpaSpecificationExecutor<Traceability> {
    
    /**
     * 根据批次号查找溯源信息
     */
    Optional<Traceability> findByBatchNumber(String batchNumber);
    
    /**
     * 根据产品ID查找所有溯源信息
     */
    List<Traceability> findByProductIdOrderByCreatedAtDesc(Long productId);
    
    /**
     * 根据二维码查找溯源信息
     */
    Optional<Traceability> findByQrCode(String qrCode);
    
    /**
     * 检查批次号是否存在
     */
    boolean existsByBatchNumber(String batchNumber);
    
    /**
     * 根据渔船信息查找溯源记录
     */
    List<Traceability> findByFishingVesselContaining(String fishingVessel);
    
    /**
     * 根据捕捞地点查找溯源记录
     */
    List<Traceability> findByFishingLocationContaining(String fishingLocation);
    
    /**
     * 查找指定产品的最新溯源信息
     */
    @Query("SELECT t FROM Traceability t WHERE t.product.id = :productId ORDER BY t.createdAt DESC")
    List<Traceability> findLatestByProductId(@Param("productId") Long productId);
}